Pointers C
The memory address of other variables, functions, or even other pointers can be stored in a pointer, which is a derived data type. It is one of the fundamental elements of the C programming language, enabling dynamic memory allocation, low-level memory access, and numerous other features.
Basic Concepts of Pointers:The value at the address included in the pointer can be accessed using the dereference operator *.
To find a variable's memory address, use the address-of operator &.
&
int x = 10;int *ptr = &x; // ptr now holds the address of x
Dereferencing a Pointer: Dereferencing a pointer means accessing the value stored at the memory address the pointer is pointing to. You use the * operator to dereference a pointer.
Example:int x = 10;int *ptr = &x;printf("%d", *ptr); // Output will be 10, as ptr points to x
Pointer to Pointer:
You can have pointers to other pointers, which means that a pointer can store the address of another pointer.
Example:
int x = 10;
int *ptr = &x;
int **ptr2 = &ptr; // ptr2 points to ptr, which points to x
printf("%d", **ptr2); // Output will be 10
Null Pointer: A pointer that does not point to any legitimate memory location is known as a null pointer. It is frequently used to show that there is no data being pointed to by the pointer.Example:int *ptr = NULL; // ptr is a null pointer
Pointer Arithmetic: Arithmetic operations are supported by pointers in C. A pointer can be increased, decreased, or even subtracted by two.
int arr[3] = {10, 20, 30};int *ptr = arr;printf("%d\n", *(ptr + 1)); // Output will be 20, points to second element
Dynamic Memory Allocation: For dynamic memory allocation and deallocation, pointers are utilized using functions such as malloc, calloc, and free.
int *ptr = (int*)malloc(sizeof(int)); // Dynamically allocate memory*ptr = 5; // Assign valueprintf("%d\n", *ptr); // Output will be 5free(ptr); // Deallocate memory
Example:
#include <stdio.h>
int main() { int a = 10; int *ptr = &a; // Pointer to the integer a
printf("Address of a: %p\n", ptr); // Print address stored in ptr printf("Value of a: %d\n", *ptr); // Dereference pointer to get value
*ptr = 20; // Modify value of a through the pointer printf("New value of a: %d\n", a); // Output will be 20
return 0;}
Comments